<template>
  <el-dialog
    :model-value="visible"
    title="物品详情"
    width="600px"
    @update:model-value="handleVisibleChange"
    @close="handleCancel"
  >
    <div v-if="item" class="detail-content">
      <!-- 基本信息 -->
      <el-descriptions title="基本信息" :column="3" border>
        <el-descriptions-item label="物品标题" :span="3">
          {{ item.title }}
        </el-descriptions-item>
        <el-descriptions-item label="物品描述" :span="3">
          {{ item.description }}
        </el-descriptions-item>
        <el-descriptions-item label="物品分类">
          <el-tag :type="getCategoryTagType(item.category)">
            {{ item.category }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="getStatusTagType(item.status)">
            {{ getStatusText(item.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发布时间">
          {{ formatTime(item.created_at) }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 发布者信息 -->
      <el-descriptions title="发布者信息" :column="3" border style="margin-top: 24px">
        <el-descriptions-item label="发布者" :span="2">
          <div class="publisher-detail">
            <el-avatar :src="item.publisher?.avatar" :size="32" />
            <span style="margin-left: 8px">{{ item.publisher?.nickname }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="联系方式">
          {{ item.contact_info }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 操作按钮 -->
      <div class="action-buttons" style="margin-top: 24px; text-align: center">
        <el-button
          v-if="isMyItem && item.status === 0"
          type="primary"
          @click="handleUpdateStatus(1)"
        >
          标记为已认领
        </el-button>
        <el-button
          v-if="isMyItem && item.status === 1"
          @click="handleUpdateStatus(0)"
        >
          重新标记为待认领
        </el-button>
        <el-button
          v-if="isMyItem"
          type="danger"
          @click="handleDelete"
          style="margin-left: 8px"
        >
          删除
        </el-button>
      </div>
    </div>

    <el-skeleton v-else :rows="5" animated />
  </el-dialog>
</template>

<script setup>
import { computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { lostAndFoundApi } from '@/api/lostandfound.js';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
const props = defineProps({
  visible: Boolean,
  item: Object
});

const emit = defineEmits(['update:visible', 'cancel', 'update']);

// 计算是否为当前用户的物品
const isMyItem = computed(() => {
  return props.item?.user_id === userStore.userInfo?.user_id;
});

// 分类标签类型映射
const getCategoryTagType = (category) => {
  const types = {
    '电子设备': 'primary',
    '学习用品': 'success',
    '生活用品': 'warning',
    '证件卡片': 'danger',
    '其他': 'info'
  };
  return types[category] || 'info';
};

// 状态标签类型映射
const getStatusTagType = (status) => {
  const types = {
    0: 'warning', // 待认领
    1: 'success',  // 已认领
    2: 'info'      // 已关闭
  };
  return types[status] || 'info';
};

// 状态文本映射
const getStatusText = (status) => {
  const texts = {
    0: '待认领',
    1: '已认领',
    2: '已关闭'
  };
  return texts[status] || '未知状态';
};

// 格式化时间
const formatTime = (time) => {
  return new Date(time).toLocaleString();
};

// 处理可见性变化
const handleVisibleChange = (value) => {
  emit('update:visible', value);
};

// 更新状态
const handleUpdateStatus = async (newStatus) => {
  try {
    const response = await lostAndFoundApi.updateStatus(props.item.item_id, newStatus);
    if (response.code === 0) {
      ElMessage.success('状态更新成功');
      emit('update');
    } else {
      ElMessage.error(response.msg || '状态更新失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试');
    console.error('更新状态失败:', error);
  }
};

// 删除物品
const handleDelete = () => {
  ElMessageBox.confirm(
    `确定要删除 "${props.item.title}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await lostAndFoundApi.delete(props.item.item_id);
      if (response.code === 0) {
        ElMessage.success('删除成功');
        emit('update');
      } else {
        ElMessage.error(response.msg || '删除失败');
      }
    } catch (error) {
      ElMessage.error('网络错误，请重试');
      console.error('删除物品失败:', error);
    }
  });
};

// 取消操作
const handleCancel = () => {
  emit('update:visible', false);
  emit('cancel');
};
</script>

<style scoped>
.detail-content {
  padding: 8px;
}

.publisher-detail {
  display: flex;
  align-items: center;
}
</style>